#include "select.hpp"
#include <algorithm>
#include "core/assert.hpp"
#include "imgui.h"

void select_item::update_data (bindable_base *data)
{
    value_->attach (data);
    options_->attach (data);
}

void select_item::init_content (const xml_node &node)
{
    ui_control::init_content (node);
    value_   = create_data (node.attribute ("value").as_string (), signed_integral | unsigned_integral);
    options_ = create_data (node.attribute ("options").as_string (), enumerate);

    PI_ASSERT_MSG (value_ && options_, "select require value,options attribute!!");
}

void select_item::draw_self ()
{

    s64         select = value_->get_s64 ();
    s64         cnt    = 0;
    enumerate_t enu    = options_->get_enumerate ();
    if (enu.count)
    {
        cnt = (s64) enu.count->get_u64 ();
    }
    if (cnt > 0)
    {
        // select = std::clamp<s64>(select, 0, cnt-1);
        const char *text = enu.text (enu.user_data, (u32) select);
        if (ImGui::BeginCombo ("##Value", text))
        {
            for (s64 i = 0; i < cnt; ++i)
            {
                text = enu.text (enu.user_data, (u32) i);
                if (ImGui::Selectable (text, i == select))
                {
                    value_->set_s64 (i);
                }
            }
            ImGui::EndCombo ();
        }
    }
    else
    {
        ImGui::BeginDisabled(true);
        if (ImGui::BeginCombo("##Value", "当前未提供可选项"))
            ImGui::EndCombo();
        ImGui::EndDisabled();
    }
}
